/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.polarrose.spring.bayeux;

import com.polarrose.spring.bayeux.util.BayeuxUtil;
import com.polarrose.spring.bayeux.util.JsonUtil;
import org.mortbay.cometd.ChannelId;
import org.mortbay.cometd.Client;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Required;

import java.util.Map;

/**
 * @author Stefan Arentz
 */

@SuppressWarnings({"unchecked"})
public class BayeuxMessageHandlerContainer implements InitializingBean
{
    /**
     *
     */

    private BayeuxController bayeuxController;

    @Required
    public void setBayeuxController(BayeuxController bayeuxController)
    {
        this.bayeuxController = bayeuxController;
    }

    /**
     *
     */

    private BayeuxChannel channel;

    @Required
    public void setChannel(BayeuxChannel channel)
    {
        this.channel = channel;
    }

    /**
     *
     */

    private BayeuxMessageHandler handler;
    
    @Required
    public void setHandler(BayeuxMessageHandler handler)
    {
        this.handler = handler;
    }

    /**
     * 
     */

    private BayeuxClient client;

    //

    /**
     * @see org.springframework.beans.factory.InitializingBean#afterPropertiesSet()
     */

    private Class<?> handlerDataClass;
    
    public void afterPropertiesSet() throws Exception
    {
        handlerDataClass = BayeuxUtil.getBayeuxMessageHandlerDataClass(handler);
        
        client = new BayeuxClient(bayeuxController, new Client(bayeuxController.getBayeux(), "idPrefix") { // TODO What is idPrefix?
            protected void deliver(Client from, ChannelId to, Map<String, Object> message) {
                Object data = message.get("data");
                if (client.getClient() != from) {
                    if (handlerDataClass != null) {
                        data = JsonUtil.transmogrify(handlerDataClass, data, null);
                    }
                    handler.handle(channel, new BayeuxClient(bayeuxController, from), data);
                }
            }
        });

        channel.addSubscriber(client);
    }
}
